<template>
  <div class="box">
    <h2>用户登录</h2>
    <el-form :model="form" :rules="rules" ref="formRef" label-width="80">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="admin" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" type="password" placeholder="123456" />
      </el-form-item>
      <el-form-item label="验证码" prop="captcha">
        <div style="display: flex;">
          <el-input v-model="form.captcha" placeholder="4位验证码" />
          <img :src="capUrl" @click="getCap" style="margin-left: 10px; height: 40px; cursor: pointer;" />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">登 录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus';

const config = useRuntimeConfig();
const router = useRouter();
const token = useCookie('token', { maxAge: 7200 });

const form = reactive({
  username: '',
  password: '',
  captcha: '',
  sid: ''
});

const rules: FormRules = {
  username: [{ required: true, message: '必填' }],
  password: [{ required: true, message: '必填' }],
  captcha: [{ required: true, len: 4, message: '4位验证码' }]
};

const formRef = ref<FormInstance>();
const capUrl = ref('');

const getCap = () => {
  form.sid = Math.random().toString(36).slice(2);
  capUrl.value = `${config.public.apiBase}/captcha?sid=${form.sid}`;
};

const submit = async () => {
  await formRef.value!.validate(async (valid) => {
    if (!valid) return;
    try {
      const res = await $fetch('/login', {
        method: 'POST',
        baseURL: config.public.apiBase,
        body: form
      });
      if (res.code === 0) {
        ElMessage.success('登录成功');
        token.value = res.data.token;
        router.push('/');
      } else {
        ElMessage.error(res.msg);
      }
    } catch (e: any) {
      ElMessage.error(e.data?.msg || '登录失败');
    }
  });
};

onMounted(() => getCap());
</script>

<style scoped>
.box {
  width: 400px;
  margin: 120px auto;
  padding: 30px;
  border: 1px solid #eee;
  border-radius: 6px;
}
</style>

